# 标准库导入
import openpyxl
from openpyxl.styles import Font
import markdown
import os

# Django框架核心导入
from django.shortcuts import render, get_object_or_404, redirect, Http404
from django.http import HttpResponse
from django.contrib import messages
from django.utils import timezone
from django.db import transaction
from django.db.models import Q
# from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Django认证相关导入
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
from django.core.exceptions import PermissionDenied

# Django通用视图
from django.views.generic import ListView, CreateView

# 本地应用导入
from .models import (
    CustomUser, Company, Department, Factory, Technology,
    Materialtype, Warehouse, Place, Material, Inventory,
    InventoryRecord, Device, DeviceHistory
)
from .forms import (
    CustomUserCreationForm, SuperCompanyForm, SuperDepartmentForm,
    SuperCustomUserCreationForm, DepartmentForm, FactoryForm,
    TechnologyForm, MaterialtypeForm, WarehouseForm, PlaceForm,
    MaterialForm, InventoryFilterForm, DeviceFilterForm,
    DeviceCreateForm, UserEditForm, InventoryRecordForm,
    DeviceAdjustForm, DeviceUpdateForm
)

# ***********************************用户登录自助界面***********************************


def user_login(request):
    """用户登录视图"""
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = authenticate(username=username, password=password)
            
            if user is not None:
                # 在登录前获取上次登录时间
                previous_login = timezone.localtime(user.last_login).strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None
                
                # 执行登录操作（Django会自动更新last_login）
                login(request, user)
                
                # 将上次登录时间存储在session中
                request.session['previous_login'] = previous_login
                messages.success(request, f'StockGo系统登录成功')
                return redirect('navigation')
            else:
                messages.warning(request, f"用户名或密码错误")
                return redirect('login')
        except Exception as e:
            messages.error(request, f"系统错误：{e}，请稍后重试")
            return redirect('login')
    return render(request, 'login.html') 

def user_logout(request):
    """用户登出视图"""
    try:
        logout(request)
        request.session.flush()
    except Exception as e:
        messages.error(request, f"登出过程中出现错误，请稍后重试")
    return render(request, 'logout.html')

@login_required
def password_change(request):
    """用户自行密码修改视图"""
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            try:
                user = form.save()
                update_session_auth_hash(request, user)  # 保持用户登录状态
                messages.success(request, '密码修改成功')
                return redirect('password_change_done')
            except Exception as e:
                messages.error(request, '密码修改过程中发生错误，请稍后重试')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'password_change.html', {'form': form})

@login_required
def navigation(request):
    """导航页面视图"""
    
    try:
        # 从session中获取上次登录时间
        previous_login = request.session.get('previous_login')

        # 计算当前用户的待办事项数量
        inventoryapproval_count = InventoryRecord.objects.filter(
            company=request.user.company,
            approvalstatus='pending'
        ).count()
        deviceapproval_count = DeviceHistory.objects.filter(
            company=request.user.company,
            approvalstatus='pending'
        ).count()

        context = {
            'last_login': previous_login,
            'inventoryapproval_count': inventoryapproval_count,
            'deviceapproval_count': deviceapproval_count
        }

        return render(request, 'navigation.html', context)
    except Exception as e:
        return HttpResponse('加载导航页面时发生错误，请稍后重试')

# ***********************************超级管理员界面***********************************

@login_required
def superuser_list(request):
    """用户列表视图"""
    if not request.user.is_superuser:
        messages.warning(request, '权限不足，无法查看管理员列表')
        return redirect('navigation')

    users = CustomUser.objects.filter(
        is_manager=1,
        is_superuser=0,
    ).order_by('-id')
    return render(request, 'superuser_list.html', {'users': users})

@login_required
@transaction.atomic
def supercompany_add(request):
    """超级管理员添加公司视图"""
    if not request.user.is_superuser:
        messages.warning(request, '权限不足，无法创建公司')
        return redirect('navigation')
    
    if request.method == 'POST':
        form = SuperCompanyForm(request.POST)
        if form.is_valid():
            try:
                with transaction.atomic():
                    # 检查公司名称是否已存在
                    company_name = form.cleaned_data['company']
                    if Company.objects.filter(company=company_name).exists():
                        messages.error(request, f'公司 {company_name} 已存在')
                        return render(request, 'supercompany_add.html', {'form': form})
                    
                    # 保存公司信息
                    company = form.save(commit=False)
                    company.save()
                    
                    messages.success(request, f'公司 {company_name} 添加成功')
                    return redirect('navigation')
                    
            except Exception as e:
                messages.error(request, f'公司添加失败: {str(e)}')
                return render(request, 'supercompany_add.html', {'form': form})
    else:
        form = SuperCompanyForm()
    
    return render(request, 'supercompany_add.html', {'form': form})

@login_required
def supercompany_list(request):
    """超级管理员地市列表视图"""
    if not request.user.is_superuser:
        messages.warning(request, '权限不足，无法查看地市列表')
        return redirect('navigation')
    
    companies = Company.objects.all().order_by('-id')
    context = {
        'companies': companies
    }
    return render(request, 'supercompany_list.html', context)

@login_required
@transaction.atomic
def superdepartment_add(request):
    """超级管理员添加县区视图"""
    if not request.user.is_superuser:
        messages.warning(request, '权限不足，无法创建县区')
        return redirect('navigation')
    
    if request.method == 'POST':
        form = SuperDepartmentForm(request.POST)
        if form.is_valid():
            try:
                with transaction.atomic():
                    # 检查同一个公司下县区名称是否已存在
                    company = form.cleaned_data['company']
                    department_name = form.cleaned_data['department']
                    if Department.objects.filter(company=company, department=department_name).exists():
                        messages.warning(request, f'公司 {company} 下已存在县区 {department_name}')
                        return render(request, 'superdepartment_add.html', {'form': form})
                    
                    # 保存县区信息
                    department = form.save(commit=False)
                    department.creator = request.user
                    department.save()
                    
                    messages.success(request, f'县区 {department_name} 添加成功')
                    return redirect('navigation')
                    
            except Exception as e:
                messages.error(request, f'县区添加失败: {str(e)}')
                return render(request, 'superdepartment_add.html', {'form': form})
    else:
        form = SuperDepartmentForm()
    
    return render(request, 'superdepartment_add.html', {'form': form})

@login_required
def superdepartment_list(request):
    """超级管理员县区列表视图(仅显示当前用户创建的记录)"""
    if not request.user.is_superuser:
        messages.warning(request, '权限不足，无法查看县区列表')
        return redirect('navigation')
    
    # 获取当前用户创建的县区记录
    departments = Department.objects.filter(creator=request.user).order_by('-id')
    context = {
        'departments': departments
    }
    return render(request, 'superdepartment_list.html', context)


@login_required
@transaction.atomic
def superuser_add(request):
    """超级管理员添加用户视图"""
    if not request.user.is_superuser:
        messages.warning(request, '权限不足，无法创建用户')
        return redirect('navigation')
    
    if request.method == 'POST':
        form = SuperCustomUserCreationForm(request.POST)
        if form.is_valid():
            try:
                with transaction.atomic():
                    # 检查用户名是否已存在
                    username = form.cleaned_data['username']
                    if CustomUser.objects.filter(username=username).exists():
                        messages.error(request, f'用户名 {username} 已存在')
                        return render(request, 'superuser_add.html', {'form': form})
                    
                    # 创建用户
                    user = form.save(commit=False)
                    user.set_password(form.cleaned_data['password1'])
                    user.save()
                    
                    messages.success(request, f'用户 {username} 添加成功')
                    return redirect('navigation')
                    
            except Exception as e:
                messages.error(request, f'用户添加失败: {str(e)}')
                return render(request, 'superuser_add.html', {'form': form})
        else:
            messages.error(request, '表单验证失败，请检查输入')
    else:
        form = SuperCustomUserCreationForm()
    
    return render(request, 'superuser_add.html', {'form': form})


# ***********************************管理员界面***********************************

# **********公共参数**********
@login_required
@transaction.atomic
def user_add(request):
    """用户添加视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法创建用户')
        return redirect('navigation')
    
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    # 检查用户名是否已存在
                    username = form.cleaned_data['username']
                    if CustomUser.objects.filter(username=username).exists():
                        messages.error(request, f'用户名 {username} 已存在')
                        return render(request, 'user_add.html', {'form': form})
                    
                    # 创建用户
                    user = form.save(commit=False)
                    user.is_manager = request.user.is_superuser
                    user.company = request.user.company
                    user.set_password(form.cleaned_data['password1'])
                    user.save()
                    
                    messages.success(request, f'用户 {username} 创建成功')
                    return redirect('user_list')
                    
            except Exception as e:
                messages.error(request, f'用户创建失败: {str(e)}')
                return render(request, 'user_add.html', {'form': form})
    else:
        form = CustomUserCreationForm(current_user=request.user)
    
    return render(request, 'user_add.html', {'form': form})

@login_required
def user_list(request):
    """用户列表视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看用户列表')
        return redirect('navigation')

    current_company = request.user.company
    users = CustomUser.objects.filter(
        is_manager=0,
        company=current_company
    ).order_by('-id')
    return render(request, 'user_list.html', {'users': users})

@login_required
def reset_password(request, user_id):
    """管理员重置用户密码视图"""

    # 获取要重置密码的用户
    try:
        user = get_object_or_404(CustomUser, id=user_id)
        if not (request.user.is_superuser or request.user.is_manager):
            messages.error(request, '权限不足，无法重置用户密码')
            return redirect('user_list')
        
        if not request.user.company == user.company:
            messages.error(request, '区域权限不足，无法编辑辖区外用户信息')
            return redirect('user_list')
            
        if user.is_superuser:
            messages.error(request, '权限级别不足，无法编辑上级管理员信息')
            return redirect('user_list')     
           
    except CustomUser.DoesNotExist:
        messages.error(request, '获取用户时发生错误，用户不存在')
        return redirect('user_list')
    
    if request.method == 'POST':
        form = SetPasswordForm(user, request.POST)
        if form.is_valid():
            try:
                form.save()
                # update_session_auth_hash(request, user)  # 保持用户登录状态
                messages.success(request, f'用户 {user.username} 的密码已重置')
                return redirect('user_list')
            except Exception as e:
                messages.error(request, f'重置密码时发生错误: {str(e)}，请稍后重试')
                return redirect('user_list')
    else:
        form = SetPasswordForm(user)
    
    return render(request, 'reset_password.html', {'form': form, 'user': user})

@login_required
@transaction.atomic
def toggle_user_active(request, user_id):
    """管理员启用/禁用用户视图"""
    try:
        with transaction.atomic():
            # 权限检查
            if not (request.user.is_superuser or request.user.is_manager):
                messages.error(request, '权限不足，无法操作用户状态')
                return redirect('user_list')
            
            # 获取要操作的用户
            user = get_object_or_404(CustomUser, id=user_id)
            
            # 检查不能操作自己的状态
            if user.id == request.user.id:
                messages.error(request, '不能修改自己的账户状态')
                return redirect('user_list')
            
            if not request.user.company == user.company:
                messages.error(request, '区域权限不足，无法编辑辖区外用户信息')
                return redirect('user_list')
            
            if user.is_superuser:
                messages.error(request, '权限级别不足，无法编辑上级管理员信息')
                return redirect('user_list')
            
            # 切换激活状态
            user.is_active = not user.is_active
            user.save()
            
            # 根据状态设置提示信息
            status = "激活" if user.is_active else "暂停使用"
            messages.success(request, f'用户 {user.username} 已{status}')
            
    except Exception as e:
        messages.error(request, f'状态切换失败: {str(e)}')
    
    return redirect('user_list')

@login_required
@transaction.atomic
def user_edit(request, user_id):
    """管理员编辑用户视图"""
    try:
        # 获取要编辑的用户
        user = get_object_or_404(CustomUser, id=user_id)
        
        # 权限检查
        if not (request.user.is_superuser or request.user.is_manager):
            messages.error(request, '没有管理权限，无法编辑用户信息')
            return redirect('user_list')

        if not request.user.company == user.company:
            messages.error(request, '区域权限不足，无法编辑辖区外用户信息')
            return redirect('user_list')
        
        if user.is_superuser:
            messages.error(request, '权限级别不足，无法编辑上级管理员信息')
            return redirect('user_list')
    
        # 检查不能编辑自己的账户
        if user.id == request.user.id:
            messages.error(request, '调整个人的权限请向上级管理员申请，不能自行修改自己的账户信息')
            return redirect('user_list')

        if request.method == 'POST':
            form = UserEditForm(request.POST, instance=user, current_user=request.user)
            if form.is_valid():
                with transaction.atomic():
                    form.save()
                    messages.success(request, f'用户 {user.username} 信息已更新')
                    return redirect('user_list')
            else:
                messages.error(request, '表单验证失败，请检查输入')
        else:
            form = UserEditForm(instance=user, current_user=request.user)
        
        return render(request, 'user_edit.html', {'form': form, 'user': user})
        
    except Exception as e:
        messages.error(request, f'用户信息更新失败: {str(e)}')
        return redirect('user_list')

@login_required
def department_add(request):
    """管理员添加县区视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法添加县区')
        return redirect('navigation')
    
    if request.method == 'POST':
        form = DepartmentForm(request.POST, current_user=request.user)
        if form.is_valid():
            department = form.save(commit=False)
            department.company = request.user.company
            department.save()
            messages.success(request, '县区添加成功')
            return redirect('department_list')
    else:
        form = DepartmentForm(current_user=request.user)
    
    return render(request, 'department_add.html', {'form': form})

@login_required
def department_list(request):
    """管理员查看县区视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看县区')
        return redirect('navigation')
    
    current_company = request.user.company
    departments = Department.objects.filter(company=current_company).order_by('department')
    return render(request, 'department_list.html', {'departments': departments})


# **********设备参数**********
@login_required
@transaction.atomic
def factory_add(request):
    """管理员添加厂家视图"""
    if request.method == 'POST':
        form = FactoryForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    factory = form.save(commit=False)
                    factory.company = request.user.company
                    # 权限检查
                    if not (request.user.is_superuser or request.user.is_manager):
                        messages.error(request, '权限不足，无法添加厂家')
                        return redirect('factory_list')
                    
                    # 检查厂家名称是否已存在
                    if Factory.objects.filter(company=request.user.company, factory=factory.factory).exists():
                        messages.error(request, f'厂家 {factory.factory} 已存在')
                        return render(request, 'factory_add.html', {'form': form})
                    
                    factory.save()
                    messages.success(request, f'{factory.factory} 厂家添加成功')
                    return redirect('factory_list')
                    
            except Exception as e:
                messages.error(request, f'厂家添加失败: {str(e)}')
                return render(request, 'factory_add.html', {'form': form})
    else:
        form = FactoryForm(current_user=request.user)
    
    return render(request, 'factory_add.html', {'form': form})

@login_required
def factory_list(request):
    """管理员查看厂家视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看厂家')
        return redirect('navigation')
    
    current_company = request.user.company
    factories = Factory.objects.filter(company=current_company).order_by('factory')
    return render(request, 'factory_list.html', {'factories': factories})

@login_required
@transaction.atomic
def technology_add(request):
    """管理员添加技术类别视图"""
    if request.method == 'POST':
        form = TechnologyForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    technology = form.save(commit=False)
                    technology.company = request.user.company
                    
                    # 权限检查
                    if not (request.user.is_superuser or request.user.is_manager):
                        messages.error(request, '权限不足，无法添加技术类别')
                        return redirect('technology_list')
                    
                    # 检查技术类别名称是否已存在
                    if Technology.objects.filter(
                        company=request.user.company,
                        technology=technology.technology
                    ).exists():
                        messages.error(request, f'技术类别 {technology.technology} 已存在')
                        return render(request, 'technology_add.html', {'form': form})
                    
                    technology.save()
                    messages.success(request, f'{technology.technology} 技术类别添加成功')
                    return redirect('technology_list')
                    
            except Exception as e:
                messages.error(request, f'技术类别添加失败: {str(e)}')
                return render(request, 'technology_add.html', {'form': form})
    else:
        form = TechnologyForm(current_user=request.user)
    
    return render(request, 'technology_add.html', {'form': form})

@login_required
def technology_list(request):
    """管理员查看技术类别视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看技术类别')
        return redirect('navigation')
    
    current_company = request.user.company
    technologies = Technology.objects.filter(company=current_company).order_by('technology')
    return render(request, 'technology_list.html', {'technologies': technologies})

@login_required
@transaction.atomic
def place_add(request):
    """管理员添加设备位置视图"""
    if request.method == 'POST':
        form = PlaceForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    place = form.save(commit=False)
                    place.company = request.user.company

                    # 检查用户权限
                    if not (request.user.is_superuser or request.user.is_manager):
                        messages.error(request, '权限不足，无法添加设备位置')
                        return redirect('place_list')
                    
                    # 检查设备位置名称是否已存在
                    if Place.objects.filter(
                        company=request.user.company,
                        place=place.place
                    ).exists():
                        messages.error(request, f'设备位置 {place.place} 已存在')
                        return render(request, 'place_add.html', {'form': form})
                    
                    place.save()
                    messages.success(request, f'{place.place}设备位置添加成功')
                    return redirect('place_list')
                    
            except Exception as e:
                messages.error(request, f'设备位置添加失败: {str(e)}')
                return render(request, 'place_add.html', {'form': form})
    else:
        form = PlaceForm(current_user=request.user)
    
    return render(request, 'place_add.html', {'form': form})

@login_required
def place_list(request):
    """管理员查看设备位置视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看设备位置')
        return redirect('navigation')
    
    current_company = request.user.company
    places = Place.objects.filter(company=current_company).order_by('-id')
    return render(request, 'place_list.html', {'places': places})


# **********物料参数**********
@login_required
@transaction.atomic
def materialtype_add(request):
    """管理员添加物料类别视图"""
    if request.method == 'POST':
        form = MaterialtypeForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    materialtype = form.save(commit=False)
                    materialtype.company = request.user.company
                    

                    # 检查用户权限
                    if not (request.user.is_superuser or request.user.is_manager):
                        messages.error(request, '权限不足，无法添加物料类别')
                        return redirect('materialtype_list')
                    
                    # 检查物料类别名称是否已存在
                    if Materialtype.objects.filter(
                        company=request.user.company,
                        materialtype=materialtype.materialtype
                    ).exists():
                        messages.error(request, f'物料类别 {materialtype.materialtype} 已存在')
                        return render(request, 'materialtype_add.html', {'form': form})
                    
                    materialtype.save()
                    messages.success(request, f'{materialtype.materialtype} 物料类别添加成功')
                    return redirect('materialtype_list')
                    
            except Exception as e:
                messages.error(request, f'物料类别添加失败: {str(e)}')
                return render(request, 'materialtype_add.html', {'form': form})
    else:
        form = MaterialtypeForm(current_user=request.user)
    
    return render(request, 'materialtype_add.html', {'form': form})

@login_required
def materialtype_list(request):
    """管理员查看物料类别视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看物料类别')
        return redirect('navigation')

    current_company = request.user.company
    materialtypes = Materialtype.objects.filter(company=current_company).order_by('materialtype')
    return render(request, 'materialtype_list.html', {'materialtypes': materialtypes})

@login_required
@transaction.atomic
def warehouse_add(request):
    """管理员添加仓库视图"""

    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法添加仓库')
        return redirect('warehouse_list')
    
    if request.method == 'POST':
        form = WarehouseForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    warehouse = form.save(commit=False)
                    warehouse.company = request.user.company
                    
                    # 检查仓库名称是否已存在
                    if Warehouse.objects.filter(company=request.user.company, warehouse=warehouse.warehouse).exists():
                        messages.warning(request, '已存在该仓库名称，请勿重复添加！')
                        return render(request, 'warehouse_add.html', {'form': form})
                    
                    warehouse.save()
                    
                    # 获取当前用户公司下所有物料
                    materials = Material.objects.filter(company=request.user.company)
                    
                    # 为每个物料创建初始库存记录
                    for material in materials:
                        Inventory.objects.create(
                            material=material,
                            warehouse=warehouse,
                            quantity=0,
                            department=warehouse.department,
                            company=request.user.company
                        )
                        
                    messages.success(request, f'{warehouse.warehouse} 仓库添加成功')
                    return redirect('warehouse_list')
                    
            except Exception as e:
                messages.error(request, f'仓库添加失败: {str(e)}')
                return render(request, 'warehouse_add.html', {'form': form})
    else:
        form = WarehouseForm(current_user=request.user)
    
    return render(request, 'warehouse_add.html', {'form': form})

@login_required
def warehouse_list(request):
    """管理员查看仓库视图"""
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看仓库')
        return redirect('navigation')
    
    current_company = request.user.company
    warehouses = Warehouse.objects.filter(company=current_company).order_by('-id')
    return render(request, 'warehouse_list.html', {'warehouses': warehouses})

@login_required
@transaction.atomic
def material_add(request):
    """管理员添加物料视图"""

    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request,  '权限不足，无法添加物料')
        return redirect('material_list')
    
    if request.method == 'POST':
        form = MaterialForm(request.POST, current_user=request.user)
        if form.is_valid():
            try:
                with transaction.atomic():
                    material = form.save(commit=False)
                    # 如果添加的同一company物料名称和已经存在，则不允许添加
                    material.company = request.user.company
                    if Material.objects.filter(company=material.company, material=material.material).exists():
                        messages.warning(request, '已存在该物料名称，请勿重复添加！')
                        form = MaterialForm(current_user=request.user)
                        return redirect('material_add')
                    
                    material.save()

                    # 获取当前用户公司下所有仓库
                    warehouses = Warehouse.objects.filter(company=request.user.company)
                    
                    # 为每个仓库创建初始库存记录
                    for warehouse in warehouses:
                        Inventory.objects.create(
                            material=material,
                            warehouse=warehouse,
                            quantity=0,
                            department=warehouse.department,
                            company=request.user.company
                        )
                    
                    messages.success(request, f'{material.material} 物料添加成功')
                    return redirect('material_list')
                    
            except Exception as e:
                messages.error(request, f'物料添加失败: {str(e)}')
                return redirect('material_add')
    else:
        form = MaterialForm(current_user=request.user)
    
    return render(request, 'material_add.html', {'form': form})

@login_required
def material_list(request):
    """管理员查看物料视图"""
    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法查看物料')
        return redirect('navigation')
    

    current_company = request.user.company
    materials = Material.objects.filter(company=current_company).order_by('-id')
    return render(request, 'material_list.html', {'materials': materials})


# **********数据导出**********
@login_required
def export_inventory(request):
    """导出库存物料清单视图"""
    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法导出库存物料清单')
        return redirect('navigation')
    
    try:
        # 获取当前用户所属公司的库存数据（增加分页或限制数量）
        inventories = Inventory.objects.filter(
            company=request.user.company
        ).select_related('material', 'warehouse', 'department')
        
        # 创建Excel工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "库存物料清单"
        
        # 设置表头
        headers = ['物料名称', '规格型号', '仓库名称', '归口部门', '库存数量', '计量单位']
        ws.append(headers)
        
        # 设置表头样式
        for cell in ws[1]:
            cell.font = Font(bold=True)
        
        # 填充数据（批量处理）
        for inv in inventories:
            try:
                ws.append([
                    inv.material.material if inv.material else '',
                    inv.material.specification if inv.material else '',
                    inv.warehouse.warehouse if inv.warehouse else '',
                    inv.department.department if inv.department else '',
                    inv.quantity,
                    inv.material.measureunit if inv.material else ''
                ])
            except Exception as e:
                continue
        
        # 设置响应头
        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename=inventory_{timezone.now().strftime("%Y%m%d")}.xlsx'
        
        # 保存Excel文件到响应
        wb.save(response)
        return response

    except Exception as e:
        messages.error(request, '导出库存清单时发生错误，请稍后重试')
        return redirect('inventory_list')

@login_required
def export_device(request):
    """导出设备使用情况视图"""
    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法导出设备数据')
        return redirect('device_list')

    try:
        # 获取当前用户所属公司的设备数据（限制最大导出数量）
        devices = Device.objects.filter(
            company=request.user.company
        ).select_related('factory', 'technology', 'place', 'department', 'create_user')
        
        # 创建Excel工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "设备使用情况"
        
        # 设置表头
        headers = ['管理编号', '规格型号', '生产厂家', '技术类别', '存放位置', '故障状态', 'MAC地址', 
                 '简要说明', '电路代号', '客户名称', '录入日期', '录入人员', '更新日期', '来源项目', 
                 '使用属性', '县区名称']
        ws.append(headers)
        
        # 设置表头样式
        for cell in ws[1]:
            cell.font = Font(bold=True)
        
        # 填充数据（添加空值检查）
        for device in devices:
            try:
                ws.append([
                    device.number,
                    device.model if device.model else '',
                    device.factory.factory if device.factory else '',
                    device.technology.technology if device.technology else '',
                    device.place.place if device.place else '',
                    device.get_state_display() if device.state else '',
                    device.mac if device.mac else '',
                    device.summary if device.summary else '',
                    device.cust_code if device.cust_code else '',
                    device.cust_name if device.cust_name else '',
                    device.create_date.strftime('%Y-%m-%d') if device.create_date else '',
                    device.create_user.username if device.create_user else '',
                    device.update_date.strftime('%Y-%m-%d') if device.update_date else '',
                    device.project if device.project else '',
                    device.get_attribute_display() if device.attribute else '',
                    device.department.department if device.department else ''
                ])
            except Exception as e:
                continue
        
        # 设置响应头
        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename=device_{timezone.now().strftime("%Y%m%d")}.xlsx'
        
        # 保存Excel文件到响应
        wb.save(response)
        return response

    except Exception as e:
        messages.error(request, '导出设备数据时发生错误，请稍后重试')
        return redirect('device_list')

@login_required
def export_inventoryrecord(request):
    """导出出入库记录视图"""
    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法导出出入库记录')
        return redirect('inventory_record_list')

    try:
        # 获取当前用户所属公司的出入库记录（限制最大导出数量）
        records = InventoryRecord.objects.filter(
            company=request.user.company
        ).select_related(
            'inventory__material',
            'inventory__warehouse',
            'department',
            'operator',
            'approver'
        )
        
        # 创建Excel工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "出入库记录"

        # 设置表头
        headers = [
            '物料名称', '规格型号', '仓库名称', '归口部门', '出入库方式', '出入库原因', '数量',
            '计量单位', '操作前数量', '操作后数量', '操作日期', '操作人',
            '审批状态', '审批人', '审批日期', '审批意见'
        ]
        ws.append(headers)

        # 设置表头样式
        for cell in ws[1]:
            cell.font = Font(bold=True)

        # 填充数据（添加空值检查）
        for record in records:
            try:
                ws.append([
                    record.inventory.material.material if record.inventory and record.inventory.material else '',
                    record.inventory.material.specification if record.inventory and record.inventory.material else '',
                    record.inventory.warehouse.warehouse if record.inventory and record.inventory.warehouse else '',
                    record.department.department if record.department else '',
                    record.get_operatemode_display() if record.operatemode else '',
                    record.reason if record.reason else '',
                    record.quantity,
                    record.inventory.material.measureunit if record.inventory and record.inventory.material else '',
                    record.quantity_before,
                    record.quantity_after,
                    record.operatedate.strftime('%Y-%m-%d') if record.operatedate else '',
                    record.operator.username if record.operator else '',
                    record.get_approvalstatus_display() if record.approvalstatus else '',
                    record.approver.username if record.approver else '',
                    record.approval_date.strftime('%Y-%m-%d') if record.approval_date else '',
                    record.approval_opinion if record.approval_opinion else ''
                ])
            except Exception as e:
                continue

        # 设置响应头
        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename=inventory_record_{timezone.now().strftime("%Y%m%d")}.xlsx'

        # 保存Excel文件到响应
        wb.save(response)
        return response

    except Exception as e:
        messages.error(request, '导出出入库记录时发生错误，请稍后重试')
        return redirect('inventory_record_list')

@login_required
def export_devicehistory(request):
    """导出设备变更记录视图"""
    # 权限检查
    if not (request.user.is_superuser or request.user.is_manager):
        messages.error(request, '权限不足，无法导出设备变更记录')
        return redirect('devicehistory_list')

    try:
        # 获取当前用户所属公司的设备变更记录（限制最大导出数量）
        histories = DeviceHistory.objects.filter(
            company=request.user.company
        ).select_related(
            'placebefore',
            'placenow',
            'departmentbefore',
            'departmentnow',
            'operator',
            'approver'
        )
        

        # 创建Excel工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "设备变更记录"

        # 设置表头
        headers = [
            '管理编号', '规格型号', '生产厂家', '技术类别', '原位置', '现位置', '原故障状态', '现故障状态',
            '变更原因', '原客户名称', '原电路代号', '申请日期', '操作人', '审批状态', '审批人',
            '审批日期', '审批意见', '原县区', '现县区'
        ]
        ws.append(headers)

        # 设置表头样式
        for cell in ws[1]:
            cell.font = Font(bold=True)

        # 预加载设备数据（减少数据库查询）
        device_numbers = [h.number for h in histories]
        devices = {d.number: d for d in Device.objects.filter(number__in=device_numbers).select_related('factory', 'technology')}

        # 填充数据（添加空值检查）
        for history in histories:
            try:
                device = devices.get(history.number)
                ws.append([
                    history.number,
                    device.model if device else '',
                    device.factory.factory if device and device.factory else '',
                    device.technology.technology if device and device.technology else '',
                    history.placebefore.place if history.placebefore else '',
                    history.placenow.place if history.placenow else '',
                    history.get_statebefore_display() if history.statebefore else '',
                    history.get_statenow_display() if history.statenow else '',
                    history.reason if history.reason else '',
                    history.cust_name if history.cust_name else '',
                    history.cust_code if history.cust_code else '',
                    history.create_date.strftime('%Y-%m-%d') if history.create_date else '',
                    history.operator.username if history.operator else '',
                    history.get_approvalstatus_display() if history.approvalstatus else '',
                    history.approver.username if history.approver else '',
                    history.approval_date.strftime('%Y-%m-%d') if history.approval_date else '',
                    history.approval_opinion if history.approval_opinion else '',
                    history.departmentbefore.department if history.departmentbefore else '',
                    history.departmentnow.department if history.departmentnow else ''
                ])
            except Exception as e:
                continue

        # 设置响应头
        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename=device_history_{timezone.now().strftime("%Y%m%d")}.xlsx'

        # 保存Excel文件到响应
        wb.save(response)
        return response

    except Exception as e:
        messages.error(request, '导出设备变更记录时发生错误，请稍后重试')
        return redirect('devicehistory_list')


# **********************************************************物料视图************************************************

class InventoryListView(ListView):
    """查看库存视图"""
    model = Inventory
    template_name = 'inventory_list.html'
    context_object_name = 'inventories'
    paginate_by = 30


    def get_queryset(self):
        # 权限检查
        if not (self.request.user.is_inventoryoperator or self.request.user.is_manager):
            messages.error(self.request, '权限不足，仅库存管理员和库存操作人可查看')
            return redirect('navigation')

        try:
            # 基础查询集 - 确保只查询当前公司的库存
            queryset = super().get_queryset().filter(company=self.request.user.company)
            
            # 获取搜索参数并进行安全处理
            search_query = self.request.GET.get('search', '').strip()
            
            # 处理筛选表单
            form = InventoryFilterForm(self.request.GET, user=self.request.user)
            if form.is_valid():
                try:
                    queryset = form.filter_queryset()
                except Exception as e:
                    messages.error(self.request, f'筛选条件处理失败，已显示全部结果: {str(e)}')
            
            # 处理搜索查询
            if search_query:
                # 将搜索字符串按空格分割成多个关键词
                keywords = search_query.split()
                for keyword in keywords:
                    try:
                        queryset = queryset.filter(
                            Q(material__material__icontains=keyword) |
                            Q(warehouse__warehouse__icontains=keyword) |
                            Q(department__department__icontains=keyword)
                        )
                    except Exception as e:
                        messages.error(self.request, f'搜索处理失败，已显示全部结果: {str(e)}')
            
            return queryset.select_related('material', 'warehouse', 'department')
            
        except Exception as e:
            messages.error(self.request, f'获取库存数据失败，请稍后重试: {str(e)}')
            return Inventory.objects.none()

    def get_context_data(self, **kwargs):

        # 权限检查
        if not (self.request.user.is_inventoryoperator or self.request.user.is_manager):
            messages.error(self.request, '权限不足，仅库存管理员和库存操作人可查看')
            return redirect('navigation')
        try:
            context = super().get_context_data(**kwargs)
            context['form'] = InventoryFilterForm(user=self.request.user)
            # 传递搜索参数回模板
            context['search_query'] = self.request.GET.get('search', '').strip()
            return context
            
        except Exception as e:
            messages.error(self.request, '页面初始化失败，请稍后重试')
            return super().get_context_data(**kwargs)



@login_required
def inventoryrecord_add(request, inventory_id):
    """通过物料清单列表，申请出入库"""
    # 权限检查
    if not (request.user.is_inventoryoperator):
        messages.error(request, '权限不足，无法申请出入库')
        return redirect('inventory_list')
    
    
    try:
        # 检查有没有计划出入库的库存物料
        inventory = Inventory.objects.select_related('material', 'warehouse', 'department').get(id=inventory_id)

        if not request.user.is_broad and request.user.department != inventory.department:
            messages.error(request, '权限不足，仅库存管理员和库存操作人可操作非本部门库存物料')
            return redirect('inventory_list')
        
        if inventory.company != request.user.company:
            messages.error(request, '权限不足，不可操作非本公司库存物料')
            return redirect('inventory_list')
        
    except Inventory.DoesNotExist:
        messages.error(request, '要操作的库存物料记录不存在')
        return redirect('inventory_list')
    except Exception as e:
        messages.error(request, f'获取库存物料失败: {str(e)}')
        return redirect('inventory_list')
    
    try:
        # 检查是否存在在途工单
        if InventoryRecord.objects.filter(inventory=inventory, approvalstatus='pending').exists():
            messages.warning(request, f"{inventory.warehouse.warehouse}{inventory.material.material}有待审批的出入库申请，请等待审批完成后再操作")

            return redirect('inventory_list')

        if request.method == 'POST':
            form = InventoryRecordForm(request.POST, inventory=inventory)
            if form.is_valid():
                try:
                    with transaction.atomic():
                        quantity = form.cleaned_data['quantity']
                        operate_mode = form.cleaned_data['operatemode']
                        outbound_modes = ['maintain', 'write_off', 'transfer_out', 'project_out', 
                                        'expired_out', 'damage_out', 'adjustment_out']
                        
                        # 检查出库数量是否超过库存
                        if operate_mode in outbound_modes and quantity > inventory.quantity:
                            messages.error(request, f"出库数量({quantity})不能大于当前库存({inventory.quantity})")
                            return render(request, 'inventoryrecord_add.html', {
                                'form': form,
                                'inventory': inventory
                            })
                            
                        # 如果不是库间调出操作
                        if operate_mode != 'transfer_out':                
                            record = form.save(commit=False)
                            record.inventory = inventory
                            record.quantity_before = inventory.quantity
                            record.operator = request.user
                            record.department = inventory.department
                            record.company = inventory.company
                            record.approvalstatus = 'pending'
                            record.save()
                            messages.success(request, f"{inventory.warehouse.warehouse}{inventory.material.material}的出入库申请已创建，等待审批")

                        # 如果是库间调拨操作
                        else:
                            transfer_warehouse = form.cleaned_data['transfer_warehouse']
                            
                            # 检查调入仓库是否与调出仓库相同
                            if transfer_warehouse == inventory.warehouse:
                                messages.error(request, "调入仓库不能与调出仓库相同")
                                return render(request, 'inventoryrecord_add.html', {
                                    'form': form,
                                    'inventory': inventory
                                })

                            # 检查调入仓库是否有该物料记录
                            transfer_inventory = Inventory.objects.get(
                                material=inventory.material, 
                                warehouse=transfer_warehouse
                            )
                            
                            # 保存调出申请
                            record = form.save(commit=False)
                            record.reason = f"从{inventory.warehouse.warehouse}调拨到{transfer_warehouse.warehouse}。" + form.cleaned_data['reason']
                            record.inventory = inventory
                            record.quantity_before = inventory.quantity
                            record.operator = request.user
                            record.department = inventory.department
                            record.company = inventory.company
                            record.approvalstatus = 'pending'
                            record.save()

                            # 保存调入申请
                            transfer_in_record = InventoryRecord(
                                inventory=transfer_inventory,
                                quantity=record.quantity,
                                quantity_before=transfer_inventory.quantity,
                                operatedate=record.operatedate,
                                reason=record.reason,
                                operatemode='transfer_in',
                                approvalstatus='pending',
                                operator=request.user,
                                department=transfer_warehouse.department,
                                company=transfer_warehouse.company
                            )
                            transfer_in_record.save()
                            messages.success(request, f"{inventory.warehouse.warehouse}{inventory.material.material}的调入申请已同步创建，等待审批")

                        return redirect('inventory_list')
                except Inventory.DoesNotExist:
                    messages.error(request, f"拟调入的 {transfer_warehouse.warehouse}没有该物料的库存记录，请联系管理员。")
                    return render(request, 'inventoryrecord_add.html', {
                        'form': form,
                        'inventory': inventory
                    })
                except Exception as e:
                    messages.error(request, f'出入库申请创建失败: {str(e)}')
                    return render(request, 'inventoryrecord_add.html', {
                        'form': form,
                        'inventory': inventory
                    })
        else:
            form = InventoryRecordForm(inventory=inventory)

        return render(request, 'inventoryrecord_add.html', {
            'form': form,
            'inventory': inventory
        })

    except Exception as e:
        messages.error(request, f'处理出入库申请时发生错误: {str(e)}')
        return redirect('inventory_list')

@login_required
def pending_inventory_list(request):
    """通过主页，显示当前用户所属公司的待审批出入库记录"""
    if not (request.user.is_approver and request.user.is_inventoryoperator):
        messages.error(request, '权限不足，无法查看待审批出入库记录')
        return redirect('navigation')
    
    # 获取当前用户所属公司的待审批出入库记录
    pending_records = InventoryRecord.objects.filter(
        approvalstatus='pending',
        company=request.user.company
    ).select_related('inventory__material', 'inventory__warehouse', 'department')

    return render(request, 'pending_inventory_record.html', {
        'pending_records': pending_records
    })

@login_required
@transaction.atomic
def approve_inventory_record(request, record_id):
    try:
        record = get_object_or_404(InventoryRecord, id=record_id)
        inventory = record.inventory
        # 权限判断
        if not (request.user.is_approver and request.user.is_inventoryoperator):
            messages.warning(request, "您没有权限执行此操作")
            return redirect('navigation')

        if request.method == 'POST':
            action = request.POST.get('action')
            approval_opinion = request.POST.get('approval_opinion', '同意')
            with transaction.atomic():
                record.approver = request.user
                record.approval_date = timezone.now()
                record.approval_opinion = approval_opinion
                if action == 'approve':
                    record.approvalstatus = 'approved'
                    if record.operatemode in ['in_stock', 'purchase', 'return', 'transfer_in', 'project_in', 'donation_in', 'adjustment_in']:
                        record.quantity_after = record.quantity_before + record.quantity
                    else:
                        record.quantity_after = record.quantity_before - record.quantity
                    record.save()

                    # 添加库存更新逻辑
                    inventory.quantity = record.quantity_after
                    inventory.save()            
                    messages.success(request, f"已批准{record.inventory.warehouse.warehouse}的{record.inventory.material.material}{record.quantity}{record.inventory.material.measureunit}的出入库申请")

                elif action == 'reject':
                    record.approvalstatus = 'rejected'
                    record.quantity_after = record.quantity_before
                    record.save()
                    messages.success(request, f"已拒绝{record.inventory.warehouse.warehouse}的{record.inventory.material.material}{record.quantity}{record.inventory.material.measureunit}的出入库记录")
                    
    except Exception as e:
        messages.error(request, "审批过程中发生错误，请稍后重试")
    return redirect('pending_inventory_list')

@login_required
def inventory_record_list(request):
    """通过主页，根据用户的区域权限显示出入库记录"""
    if not (request.user.is_inventoryoperator):
        messages.error(request, '权限不足，无法查看出入库记录')
        return redirect('navigation')
    
    user = request.user

    if not user.is_broad:
        records = InventoryRecord.objects.filter(
            department=user.department
        ).select_related(
            'inventory__material', 'inventory__warehouse', 'department', 'company'
        ).order_by('-id')[:50] 
    else:
        # 显示所属地市等于用户所在公司的记录
        records = InventoryRecord.objects.filter(
            company=user.company
        ).select_related(
            'inventory__material', 'inventory__warehouse', 'department', 'company'
        ).order_by('-id')[:50]

    return render(request, 'inventory_record_list.html', {'records': records})

@login_required
def inventoryhistory_list(request, inventory_id):
    """通过库存物料列表页面，点击查看该物料所有出入库记录"""
    if not (request.user.is_inventoryoperator):
        messages.error(request, '权限不足，无法查看出入库记录')
        return redirect('navigation')
    # 获取 inventory 对象
    inventory = get_object_or_404(Inventory, id=inventory_id)

    # 查询该 inventory 的所有出入库记录
    records = InventoryRecord.objects.filter(
        inventory=inventory
    ).select_related('inventory__warehouse', 'operator').order_by('-id')[:50]

    return render(request, 'inventoryhistory_list.html', {
        'records': records,
        'inventory': inventory
    })

 
# **********************************************************设备视图************************************************

class DeviceListView(ListView):
    """查看设备视图"""
    model = Device
    template_name = 'device_list.html'
    context_object_name = 'devices'
    paginate_by = 30

    def get_queryset(self):
        if not (self.request.user.is_deviceoperator):
            messages.error(self.request, '权限不足，无法查看设备信息')
            return redirect('navigation')
        
        queryset = super().get_queryset().filter(company=self.request.user.company)
        
        # 获取搜索参数并去除首尾空格
        search_query = self.request.GET.get('search', '').strip()
        
        if search_query:
            # 将搜索字符串按空格分割成多个关键词
            keywords = search_query.split()
            for keyword in keywords:
                # 对每个关键词进行多字段模糊搜索
                queryset = queryset.filter(
                    Q(number__icontains=keyword) |
                    Q(model__icontains=keyword) |
                    Q(factory__factory__icontains=keyword) |
                    Q(technology__technology__icontains=keyword) |
                    Q(place__place__icontains=keyword) |
                    Q(cust_name__icontains=keyword)
                )
        
        # 保留原有的筛选表单逻辑
        form = DeviceFilterForm(self.request.GET, user=self.request.user)
        if form.is_valid():
            queryset = form.filter_queryset(queryset)
            
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = DeviceFilterForm(user=self.request.user)
        # 传递搜索参数回模板
        context['search_query'] = self.request.GET.get('search', '')
        return context


class DeviceCreateView(CreateView):
    """添加设备视图"""
    model = Device
    form_class = DeviceCreateForm
    template_name = 'device_create.html'

    def get_form_kwargs(self):
        # 权限检查
        if not (self.request.user.can_add_device):
            messages.error(self.request, '权限不足，无法添加设备')
            return redirect('navigation')
            
        # 将当前用户传递给表单
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):
        try:
            with transaction.atomic():
                device = form.save(commit=False)
                place = form.cleaned_data['place']
                
                # 验证设备编号是否已存在
                if Device.objects.filter(number=device.number).exists():
                    form.add_error('number', '该设备编号已存在')
                    return self.form_invalid(form)
                
                device.company = place.company
                device.department = place.department
                device.attribute = place.attribute
                device.create_user = self.request.user
                device.create_date = timezone.now()
                device.save()
                
                messages.success(self.request, f'编号为{device.number}的设备添加成功')
                return redirect('device_list')
                
        except Exception as e:
            messages.error(self.request, f'设备添加失败: {str(e)}')
            return self.form_invalid(form)

@login_required
def device_adjust(request, pk):
    try:
        device = get_object_or_404(Device, pk=pk)
        
        if not (request.user.is_deviceoperator):
            messages.error(request, '权限不足，无法调整设备')
            return redirect('navigation')
        # 检查权限
        if not request.user.is_broad and request.user.department != device.department:
            messages.error(request, '您没有权限调整此设备')
            return redirect('device_list')
        
        if not request.user.is_superuser and request.user.company != device.company:
            messages.error(request, '您没有权限调整此设备')
            return redirect('device_list')
        
        # 检查是否已有待审批的调整记录
        if DeviceHistory.objects.filter(number=device.number, approvalstatus='pending').exists():
            messages.warning(request, f'编号为{device.number}的设备当前有待审批的位置调整申请，请等待审批完成后再操作。')
            return redirect('device_list')

        if request.method == 'POST':
            form = DeviceAdjustForm(request.POST, instance=device)
            
            if form.is_valid():
                placenow = form.cleaned_data['placenow']
                statenow = form.cleaned_data['statenow']
                
                # 检查新位置是否与原位置相同
                if str(device.place.id) == str(placenow.id) and str(device.state) == str(statenow):
                    messages.warning(request, f'{device.number}新位置新状态不能与原位置原状态完全相同，请重新执行调度。')
                    return redirect('device_list')
                
                try:
                    with transaction.atomic():
                        DeviceHistory.objects.create(
                            number=device.number,
                            cust_code=device.cust_code,
                            cust_name=device.cust_name,
                            placebefore=device.place,
                            placenow=placenow,
                            statebefore=device.state,
                            statenow=statenow,
                            reason=form.cleaned_data['reason'],
                            create_date=timezone.now().date(),
                            operator=request.user,
                            approvalstatus='pending',
                            departmentbefore=device.department,
                            departmentnow=placenow.department,
                            company=device.company
                        )
                        messages.success(request, f'编号为{device.number}的设备调整申请已提交，请等待审批。')
                        return redirect('device_list')
                except Exception as e:
                    messages.error(request, f'创建调整记录失败: {str(e)}')
                    return redirect('device_list')
        else:
            form = DeviceAdjustForm(instance=device)
            # 获取用户关联的区域，限制位置选择只能是用户管辖区域内的位置
            if not request.user.is_broad:
                form.fields['placenow'].queryset = Place.objects.filter(department=request.user.department)
            else:
                form.fields['placenow'].queryset = Place.objects.filter(company=request.user.company)

        return render(request, 'device_adjust.html', {'form': form, 'device': device})
    except Exception as e:
        messages.error(request, f'系统错误: {str(e)}')
        return redirect('device_list')

@login_required
def pending_devicehistory(request):

    if not (request.user.is_approver and  request.user.is_deviceoperator):
        messages.error(request, '权限不足，无法查看待审批的出入库记录')
        return redirect('navigation')
    
    # 获取当前用户所属公司的待审批出入库记录
    pending_records = DeviceHistory.objects.filter(
        approvalstatus='pending',
        company=request.user.company  
    )
    
    return render(request, 'pending_devicehistory.html', {'pending_records': pending_records})

@login_required
def devicehistory_list(request):

    if not request.user.is_deviceoperator:
        messages.error(request, '权限不足，无法查看设备历史记录')
        return redirect('navigation')
    
    # 初始化查询集 - 限制只能查看用户管理的区域内的设备历史记录
    if not request.user.is_broad:
        places = Place.objects.filter(department=request.user.department)
        histories = DeviceHistory.objects.filter(
            Q(departmentbefore=request.user.department) |
            Q(departmentnow=request.user.department)
            ).order_by('-id')[:50] 
    else:
        places = Place.objects.filter(company=request.user.company)
        histories = DeviceHistory.objects.filter(company=request.user.company).order_by('-id')[:50] 
    
    # 处理筛选条件
    selected_placebefore = request.GET.get('placebefore')
    selected_placenow = request.GET.get('placenow')
    
    if selected_placebefore:
        histories = histories.filter(placebefore=selected_placebefore)
    if selected_placenow:
        histories = histories.filter(placenow=selected_placenow)
    
    return render(request, 'devicehistory_list.html', {
        'histories': histories,
        'places': places,
        'selected_placebefore': selected_placebefore,
        'selected_placenow': selected_placenow
    })


@login_required
def approve_device(request, pk):
    record = get_object_or_404(DeviceHistory, pk=pk)
    device = get_object_or_404(Device, number=record.number)
    
    # 权限判断
    if not (request.user.is_approver and request.user.is_deviceoperator):
        messages.warning(request, "您没有权限执行此操作")
        return redirect('pending_inventory_list')
    
    if request.method == "POST":
        action = request.POST.get('action')
        approval_opinion = request.POST.get('approval_opinion', '同意')
        record.approver = request.user
        record.approval_date = timezone.now()
        record.approval_opinion = approval_opinion
        if action == 'approve':
            record.approvalstatus = 'approved'
            record.save()

            # 更新设备表
            device = get_object_or_404(Device, number=record.number)
            device.place = record.placenow
            device.state = record.statenow
            device.update_date = timezone.now().date()
            device.attribute = record.placenow.attribute
            device.department = record.departmentnow
            device.save()
            messages.success(request, f"已批准编号为{record.number}的设备位置变更申请")
        elif action == 'reject':
            record.approvalstatus ='rejected'
            record.save()
            messages.success(request, f"已拒绝编号为{record.number}的设备位置变更申请")
    return redirect('pending_devicehistory')


@login_required
def device_detail(request, device_id):
    device = get_object_or_404(Device, id=device_id)

    if not request.user.is_deviceoperator:
        messages.warning(request, "您没有管理权限执行此操作")
        return redirect('device_list')
    if not request.user.is_broad and device.department != request.user.department:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    if not request.user.is_superuser and device.company != request.user.company:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    
    return render(request, 'device_detail.html', {'device': device})

@login_required
def devicehistory_detail(request, device_number):
    if not request.user.is_deviceoperator:
        messages.warning(request, "您没有管理权限执行此操作")
        return redirect('device_list')
    
    device = get_object_or_404(Device, number=device_number)

    if not request.user.is_broad and device.department != request.user.department:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    
    if not request.user.is_superuser and device.company != request.user.company:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    
    histories = DeviceHistory.objects.filter(number=device_number).order_by('-create_date')
    return render(request, 'devicehistory_detail.html', {'histories': histories})


@login_required
def device_edit(request, device_id):
    device = get_object_or_404(Device, id=device_id)
    if not request.user.is_deviceoperator:
        messages.warning(request, "您没有管理权限执行此操作")
        return redirect('device_list')
    if not request.user.is_broad and device.department != request.user.department:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    if not request.user.is_superuser and device.company != request.user.company:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    if request.method == 'POST':
        form = DeviceUpdateForm(request.POST, instance=device)
        if form.is_valid():
            device = form.save(commit=False)
            device.save()
            return redirect('device_detail', device_id=device.id)
    else:
        form = DeviceUpdateForm(instance=device)
    
    return render(request, 'device_edit.html', {'form': form})

@login_required
def device_detail_pending(request, number):
    device = get_object_or_404(Device, number=number)

    if not (request.user.is_deviceoperator and request.user.is_approver):
        messages.warning(request, "您没有管理权限执行此操作")
        return redirect('device_list')
    if not (request.user.is_broad and device.department != request.user.department):
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    if not request.user.is_superuser and device.company != request.user.company:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')

    return render(request, 'device_detail_pending.html', {'device': device})

@login_required
def pendingdevicehistory_detail(request, number):

    device = get_object_or_404(Device, number=number)
    
    if not (request.user.is_deviceoperator and request.user.is_approver):
        messages.warning(request, "您没有管理权限执行此操作")
        return redirect('device_list')
    if not request.user.is_broad and device.department != request.user.department:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')
    if not request.user.is_superuser and device.company != request.user.company:
        messages.warning(request, "您没有区域权限执行此操作")
        return redirect('device_list')

    # 获取最新的待审批记录
    histories = DeviceHistory.objects.filter(number=number)
    if not histories:
        raise Http404("未找到对应的设备调整记录")
    return render(request, 'pendingdevicehistory_detail.html', {'histories': histories})

@login_required
def help_page(request):
    try:
        # 从根目录读取Operate_Mannual.md文件
        markdown_file_path = os.path.join(os.getcwd(), 'Operate_Mannual.md')
        
        with open(markdown_file_path, 'r', encoding='utf-8') as file:
            markdown_content = file.read()
        
        html_content = markdown.markdown(markdown_content)
        
        # 修改模板路径
        template_path = 'help_page.html'
        
        # 返回渲染后的模板
        return render(request, template_path, {'html_content': html_content})
    except FileNotFoundError as e:
        return HttpResponse("Markdown 文件未找到。", status=404)
    except Exception as e:
        return HttpResponse(f"发生错误: {str(e)}", status=500) 
    
def feature_not_available(request):
    return render(request, 'feature_not_available.html')